<template>
  <view class="content">
		<view>
			<personalInfo :name="nickName" :standing="role"  />
		</view>
		<view style="height: 100vh;width: 100vw;">
			<content v-if="showState === 'content'" :allType="allType" :receiveOrder="receiveOrder" :dayNum="dayNum"></content>
			<person v-if="showState === 'person'"></person>
		</view>
		<view class="fix_bar">
			<Bar @changeState="changeState" :showState="showState" />
		</view>
	</view>
    
</template>
<script>
import content from '../pagesAll/content.vue'
import person from '../pagesAll/person.vue'
import Bar from '../../pagesScreen/pagesCompontents/tabBars/index.vue';
import personalInfo from '../../pagesScreen/pagesCompontents/personal-info.vue'
import { needMonney,taskList,dispatchOrganic, driverCount, getNearFarm, experCategory, experCurrent, experTotal, lastTime, farmBord, organicType, farmEcharts, days, collect, estimated, stats, task, dispatcherEcharts, workNum, ordNum, farmIndex, farmMonery ,farmOrder} from '../../common/example.js';
import qiunDataCharts from '@/pagesScreen/subpackageuni/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue'
export default {
  components: {
    qiunDataCharts,
    personalInfo,
    content,
    person,
    Bar
  },
  data() {
    return {
      runningFarm:0,
      waitFarm:0,
      showState: 'content',
      naes:'qwer',
      isPay:0,
      noPay:0,
      showModal: false,
      indent: '',
      expert: [
        {
          title: '已完成任务数', value: 0
        },
        {
          title: '未完成任务数', value: 0
        }
      ],
      lastFeedbackTime: '',//最新反馈时间
      test: {
        unstarted: 0,
        completed: 0
      },
      allType: [],
      base: '',
      array: [],
      index: 0,
      farmChart: {
        type: '',
        date: ''
      },
      yj: {
        text1: '',
        weight1: 0,
        text2: '',
        weight2: 0
      },
      driver: {
        type: 'week'
      },
      money: {
        a: 0,
        b: 0,
      },
      predicOrganicWeightVOList: [],//养殖场预计
      todayOrganicWeightVOList: [],//养殖场今日
      totalOrganicWeightVOList: [],//养殖场累计
      indexs: 0,
      state: false,
      receiveOrder: 0,//待接
      indexss: 0,//养殖场图表日期切换
      week: ['周', '月', '年'],
      alDay: '',//已加入天数
      nickName: '',//昵称
      driverdung: 0,//司机收集牛粪
      driversewage: 0,//司机收集污水
      dung: 0,//牛粪
      sewage: 0,//污水
      predictDung: 0,//预计收集牛粪
      predictSewage: 0,//预计收集污水
      leisure: 0,//空闲
      running: 0,//收运中
      fault:0,//报停中
      pending: 0,//待接单
      aleardy: 0,//已完成
      worknums: 0,//接受工单次数
      dayNum: 0,//今日已接
      dNum: 0,//待接单
      userInfo: {},
      flag: true,
      role: '',//处理厂司机/养殖场账号
      chartData: {},
      currentPage: '',
      opts: {
        color: [
          "#18512c"
        ],
        padding: [15, 15, 0, 5],
        enableScroll: false,
        legend: {},
        xAxis: {
          disableGrid: true,
        },
        yAxis: {
          data: [
            {
              min: 0,
            },
          ],
        },
        extra: {
          column: {
            type: "group",
            width: 30,
            activeBgColor: "#000000",
            activeBgOpacity: 0.08,
          },
        },
      },
      lat: '',
      lon: '',
      kmValue: '',
      kmUnit: '',
      fillOrd: {},
      dispatch: {
        organicType: null,
        type: 'week'
      },
      indexDis: 0
    };
  },
  methods: {
    falist() {
      farmOrder({}).then(res => {
        console.log(res.data, '预约记录');
        if (res.data.code == 200) {
          this.runningFarm = res.data.data.filter((item)=>item.appointDetailState == 1).length;
          this.waitFarm = res.data.data.filter((item)=>item.appointDetailState === 0).length;
        }
      })
    },
    changeState (state) {
			this.showState = state
		},
    bindPickerChange: function (e) {
      let t = this;
      console.log('picker发送选择改变，携带值为', e.detail.value)
      let index = e.detail.value;
      console.log(t.array[e.detail.value], 't.range[index]');
      t.farmChart.type = t.array[index];
      t.chartsFarm(this.farmChart.date);
    },
    bindPickerDispatch(e) {
      let t = this;
      console.log('picker发送选择改变，携带值为', e.detail.value)
      let value = e.detail.value;
      console.log(t.array[value], 't.range[t.index]');
      t.dispatch.organicType = t.array[value];
      this.chartsDiapatch(t.dispatch);
    },
    webs() {
      let url = 'https://pro.surveyking.cn/s/wkT0OO'
      uni.navigateTo({
        url: '/pagesDispatch/index/webview?url=' + url
      })
    },
    // 缴费
    fee() {
      uni.navigateTo({ url: '/pagesFarmer/index/fees' })
    },
    // 查看工单
    looks() {
      if (this.receiveOrder == 0) {
        uni.showToast({
          title: '当前暂无工单',
          icon: 'none',
          mask: true
        })
      } else {
        uni.navigateTo({ url: '/pagesDriver/system/workOrder' })
      }

    },
    //   提交
    submit() {
      let t = this;
      console.log(t.kmUnit, t.kmValue);
      if (t.kmValue < 1000 && t.kmUnit == 'm') {
        uni.navigateTo({ url: '/pagesDriver/system/filling' });
        console.log(this.fillOrd);
        
        uni.setStorageSync('fillWork', this.fillOrd)
      } else {
        t.showModal = true;
      }
      return;
    },
    refresh() {
      const getLocationAsync = () => {
        return new Promise((resolve, reject) => {
          uni.getLocation({
            type: 'gcj02',
            success: function (res) {
              resolve(res); // 将位置信息传递给resolve
            },
            fail: function (err) {
              reject(err); // 处理获取位置失败的情况
            }
          });
        });
      };
      (async () => {
        try {
          const location = await getLocationAsync(); // 等待获取位置信息
          console.log(location, 'location'); // 输出位置信息到控制台

          // 调用getNearFarm并传递位置信息
          const response = await getNearFarm({
            lat: location.latitude,
            lon: location.longitude
          });

          console.log(response.data, 'response'); // 输出getNearFarm的响应数据到控制台
          if (response.data.code == 200) {
            this.kmValue = response.data.data.distance;
            this.kmUnit = response.data.data.unit;
            this.fillOrd = response.data.data.workOrderDetail;
            this.fillOrd.farmName = response.data.data.farmName;
            this.fillOrd.licenseNumber = response.data.data.licenseNumber;
            uni.showToast({
              title: '已重新定位',
              icon: 'none'
            })
            if (this.kmValue < 1000 && this.kmUnit == 'm') {
              this.showModal = false;
            }
            console.log(this.kmValue);
          } else {
            uni.showToast({
              title: response.data.msg,
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('Error:', error); // 处理可能的错误
        }
      })();
    },

    // 管理
    manage() {
      uni.navigateTo({ url: '/pagesDispatch/index/quest' })
    },
    carStop() {
      uni.navigateTo({ url: '/pagesDriver/system/carStop' })
    },
    toggleIndex(i, index) {
      this.indexs = index;
      this.chartsWeek(i);
    },
    // 养殖场日期切换
    toggleIndexs(i, index) {
      this.indexss = index;
      this.chartsFarm(i);
    },
    //调度员图表日期切换
    toggleDispatch(i, index) {
      this.indexDis = index;
      if (i == '周') {
        this.dispatch.type = 'week';
        this.chartsDiapatch(this.dispatch);
      } else if (i == '月') {
        this.dispatch.type = 'month';
        this.chartsDiapatch(this.dispatch);
      } else {
        this.dispatch.type = 'year';
        this.chartsDiapatch(this.dispatch);
      }
    },
    //司机图表日期切换
    toggleIndexCar(i, index) {
      this.indexs = index;
      console.log(i, 'i');
      if (i == '周') {
        this.driver.type = 'week';
        this.chartsCar(this.driver.type);
      } else if (i == '月') {
        this.driver.type = 'month';
        this.chartsCar(this.driver.type);
      } else {
        this.driver.type = 'year';
        this.chartsCar(this.driver.type);
      }
    },
    chartsDiapatch(i) {
      dispatcherEcharts({
        type: i.type,
        organicType: i.organicType
      }).then(response => {
        console.log(response.data, '调度员图表');
        const week = response.data.data.map((item) => item.name)
        const value = response.data.data.map((item) => item.value);
        let res = {
          categories: week,
          series: [
            {
              name: '收运量(吨)',
              data: value
            }
          ]
        }
        this.chartData = JSON.parse(JSON.stringify(res));
      })

    },
    chartsFarm(i) {
      console.log(i, 'iiiiiii');

      if (i == '周') {
        this.farmChart.date = 7;
      } else if (i == '月') {
        this.farmChart.date = 30;
      } else if (i == '年') {
        this.farmChart.date = 365;
      }
      // 养殖场图表
      if (!i) {
        farmEcharts({
          organicType: this.farmChart.type,
          timeSort: 7,
        }).then(response => {
          console.log(response.data, '养殖场图表');
          const week = response.data.data.map((item) => item.timeNumber)
          const value = response.data.data.map((item) => item.totalValue);
          let res = {
            categories: week,
            series: [
              {
                name: '收运量(吨)',
                data: value
              }
            ]
          }
          this.chartData = JSON.parse(JSON.stringify(res));
        })
      } else if (i == '月') {
        farmEcharts({
          organicType: this.farmChart.type,
          timeSort: this.farmChart.date,
        }).then(response => {
          console.log(response.data, '养殖场图表');
          const week = response.data.data.map((item) => item.timeNumber)
          const value = response.data.data.map((item) => item.totalValue);
          let res = {
            categories: week,
            series: [
              {
                name: '收运量',
                data: value
              }
            ]
          }
          this.chartData = JSON.parse(JSON.stringify(res));
        })
      } else if (i == '年') {
        farmEcharts({
          organicType: this.farmChart.type,
          timeSort: this.farmChart.date,
        }).then(response => {
          console.log(response.data, '养殖场图表');
          const week = response.data.data.map((item) => item.timeNumber)
          const value = response.data.data.map((item) => item.totalValue);
          let res = {
            categories: week,
            series: [
              {
                name: '收运量',
                data: value
              }
            ]
          }
          this.chartData = JSON.parse(JSON.stringify(res));
        })
      } else {
        farmEcharts({
          organicType: this.farmChart.type,
          timeSort: 7,
        }).then(response => {
          console.log(response.data, '养殖场图表');
          const week = response.data.data.map((item) => item.timeNumber)
          const value = response.data.data.map((item) => item.totalValue);
          let res = {
            categories: week,
            series: [
              {
                name: '收运量',
                data: value
              }
            ]
          }
          this.chartData = JSON.parse(JSON.stringify(res));
        })
      }

    },
    chartsCar(i) {
      console.log(i, '司机的i');
      driverCount(i).then(response => {
        console.log(response.data, '司机图表');
        const week = response.data.data.map((item) => item.name)
        const value = response.data.data.map((item) => item.value);
        let res = {
          categories: week,
          series: [
            {
              name: '收运量(吨)',
              data: value
            }
          ]
        }
        this.chartData = JSON.parse(JSON.stringify(res));
      })
    }
  },
  onShow() {
    this.kmUnit = '';
    this.kmValue = '';
    // driverCount({}).then(res=>{
    //   console.log(res,'res----------------');
    // })
    
    uni.hideHomeButton();
    this.indent = uni.getStorageSync('pageIndent');
    this.role = uni.getStorageSync('userInfo').remark;
    this.nickName = uni.getStorageSync('userInfo').nickName;
    console.log(this.nickName);
    
    farmBord({
      userType: this.role == '养殖场账号' ? 'farmer' : this.role == '处理厂司机' || this.role == '调度员司机' ? 'driver' : this.role == '调度员' ? 'dispatcher' : ''
    }).then(res => {
      // console.log(res.data,'有机质类型');
      if (res.data.code == 200) {
        this.allType = res.data.data;
      } else {
        this.allType = [{
          name:'暂无',
          value:0
        }];
      }
      console.log(this.allType, 'allType');
    })

    if (this.role == '处理厂司机') {
      // this.chartsCar(this.driver.type)
      taskList({workOrderDetailState:''}).then(res=>{
        console.log(res.data,'列表');
        if(res.data.code==200){
          let arr  = res.data.data.filter((item)=>item.workOrderState!=2);
          if(arr.length>=1){
            uni.setStorageSync('licenseNumber',[arr[0].licenseNumber]);
          }
          console.log(arr,'arr');
        }
      })
      // 接受工单
      workNum({}).then(res => {
        console.log(res.data, '接受工单');
        if (res.data.code == 200) {
          this.worknums = res.data.data.orderTotal;
          this.driversewage = res.data.data.sewageTotal || 0;
          this.driverdung = res.data.data.cowDungTotal || 0;
        }
      });
      ordNum({}).then(res => {
        console.log(res.data, '待接工单');
        if (res.data.code == 200) {
          this.dNum = res.data.data.dNum || 0;
          this.dayNum = res.data.data.todayTotalOrder || 0;
          this.receiveOrder = res.data.data.receiveOrder || 0;
          console.log(this.receiveOrder, 'receiveOrder');
          if (this.receiveOrder > 0) {
            // this.flag = false;
          }
        }
      })

    } else if (this.role == '调度员') {
      this.chartsDiapatch(this.dispatch);
      dispatchOrganic().then(res => {
        console.log(res.data, '调度员有机质');
        if (res.data.code == 200) {
          this.array = res.data.data;
        }
      })
    } else if (this.role == '养殖场账号') {
      organicType().then(res => {
        console.log(res.data, '有机质类型');
        if (res.data.code == 200) {
          this.array = res.data.data;
        }
      })
      this.falist();
      // 养殖场首页
      farmIndex().then(res => {
        console.log(res.data, '养殖场首页');
        if (res.data.code == 200) {
          this.predicOrganicWeightVOList = res.data.data.predicOrganicWeightVOList;
          this.todayOrganicWeightVOList = res.data.data.todayOrganicWeightVOList;
          this.totalOrganicWeightVOList = res.data.data.totalOrganicWeightVOList;
          this.yj.text1 = this.predicOrganicWeightVOList[0].organicType;
          this.yj.weight1 = this.predicOrganicWeightVOList[0].organicWeight;
          this.yj.text2 = this.predicOrganicWeightVOList[1].organicType;
          this.yj.weight2 = this.predicOrganicWeightVOList[1].organicWeight;
        }
      })
      //缴费
      // farmMonery({}).then(res => {
      //   console.log(res.data, '费用');
      //   this.money.a = res.data.data.newMoney;
      //   this.money.b = res.data.data.oldMoney;
      // })
      needMonney({}).then(res=>{
        console.log(res.data,'待缴费');
        this.isPay = res.data.data.isPay;
        this.noPay = res.data.data.noPay;
      })
      // 有机质类型

      // 养殖场账号
      this.chartsFarm();
    } else if (this.role == '实验员' || this.role == '任务发布实验员' || this.role == '任务分配实验员') {
      lastTime().then(res => {
        console.log(res, '最新反馈时间');
        this.lastFeedbackTime = res.data.data.lastFeedbackTime;
      });
      experTotal().then(res => {
        console.log(res.data, '总累计');
        this.expert[0].value = res.data.data.completed;
        this.expert[1].value = res.data.data.unCompleted;
      })
      experCurrent().then(res => {
        console.log(res, '待开始');
        this.test.unstarted = res.data.data.unstarted;
        this.test.completed = res.data.data.completed;
      })
      experCategory().then(res => {
        console.log(res, '实验类型列表');
      })
    }
    // 已加入
    days({}).then(res => {
      console.log(res.data, '已加入');
      if (res.data.code == 200) {
        this.alDay = res.data.data || 0
      }
    })
    // 收集
    collect({}).then(res => {
      console.log(res.data, '已收集');
      if (res.data.code == 200) {
        this.sewage = res.data.data.sewage || 0;
        this.dung = res.data.data.dung || 0;
      }
    })
    // 预计待收集
    estimated({}).then(res => {
      console.log(res.data, '预计待收集');
      if (res.data.code == 200) {
        this.predictSewage = res.data.data.sewage || 0;
        this.predictDung = res.data.data.dung || 0;
      }
    })
    // 收运车辆统计
    stats({}).then(res => {
      console.log(res.data, '收运车辆统计');
      if (res.data.code == 200) {
        this.leisure = res.data.data.leisure || 0;
        this.running = res.data.data.running || 0;
        this.fault = res.data.data.fault || 0;
      }
    })
    // 待接单
    task({}).then(res => {
      console.log(res.data, '任务');
      if (res.data.code == 200) {
        this.aleardy = res.data.data.completed || 0;
        this.pending = res.data.data.uncompleted || 0;
      }
    })
    var pages = getCurrentPages();
    let currentPageRoute = pages[pages.length - 1].route;
    this.currentPage = currentPageRoute;
  },
  onLoad() {

  }
};
</script>
<style lang="scss">
.content {
		display: flex;
		flex-direction: column;
		background-color: #f2f8f5;
		min-height: 100vh;
	}
	.fix_bar {
		position: fixed;
		bottom: 40rpx;
		left: 0;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
page {
  background-color: #f2f8f5;
}

.container {
  // background: #f6f3e7;
  height: 100%;
  // max-height: 91vh;
  // overflow-y: scroll;
  // position: absolute;
  // left: 0;
  width: 100vw;
}

.carStop {
  text-align: center;
}

.carStop image {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.card {
  border: 3px solid #1a512c;
  border-radius: 10px;
}

.center-bg {
  background: #1a512c;
  color: #fff;
  // width: 95%;
  // margin-left: 2.5%;
  border-radius: 10px;
}

.charts-box {
  width: 100%;
  // height: 230px;
  position: relative;
  // z-index: 1;
}

.foot-card {
  background: #fff;
  border-radius: 10px;
}

.look {
  background: #1a512c;
  color: #fff;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.looks {
  background: #D0463F;
  color: #fff;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tabBar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100vw;
  height: 9vh;
}

.roundDate {
  border-radius: 50%;
  border: 2px solid #1A512C;
  height: 75rpx;
  font-weight: 600;
  width: 75rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1A512C;
  background-color: #F6F3E7
}

.active {
  background: #1A512C;
  color: #fff;
}

.border-max {
  border: 2px solid #1a512c;
  border-radius: 5px;
  text-align: center;
  width: 100%;
}

.warp {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.rect {
  width: 90vw;
  // height: 120px;
  background-color: #ffffff;
  border-radius: 10px;
}

.km {
  color: #000000;
  font-size: 17px;
  font-weight: 600;
  text-align: center;
}

.refresh {
  width: 150rpx;
  height: 150rpx;
  border-radius: 50%;
  color: #fff;
  background: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tip {
  font-size: 14px;
  color: #999999;
  text-align: center;
  font-weight: 500;
}
</style>